package c.x.jy.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 
 * @ClassName: StringTools 
 * @Description: 字符串工具类
 *  
 */
@SuppressWarnings("all")
public class StringTools {
	
	public static boolean isEmpty(String s){
		return s==null || "".equals(s.trim());
	}
	
	
	public static boolean isAnyEmpty(Object... s){
		for (Object str : s) {
			if(str==null || "".equals(str)){
				return true;
			}
		}
		return false;
	}
	
	/**
	* @Title: generateNum 
	* @Description: 生成4位随机数
	* @param @return   
	* @return String   
	* @throws
	 */
	public static String generateNum() {
		return generateRandomWord(4,false);
	}
	
	/**
	* @Title: generateRandomWord 
	* @Description: 生成n位随机数 (n<=8)，包含字母
	* @param @return   
	* @return String   
	* @throws
	 */
	public static String generateRandomWord(int n,boolean usechar) {
		if(n>8){
			n = 8;
		}
		String[] nums = new String[] { "0","1","2", "3", "4", "5", "6", "7","8", "9"};
		String[] chars = new String[] {  "0","1","2", "3", "4", "5", "6", "7","8", "9" ,"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
				"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
				"W", "X", "Y", "Z" };
		String[] beforeShuffle = nums;
		if(usechar){
			beforeShuffle = chars;
		}
		List list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}
		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(2, 2+n);
		return result;
	}
	
	/**
	 * @Title: generateGuid 
	* @Description: 生成GUID
	* @param @return   
	* @return String   
	* @throws
	 */
	public static String generateGuid(){
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replaceAll("-", "");
	}

	public static String encryptPasswd(String passwd,String guid){
		passwd = EncryptUtils.MD5(passwd);
		passwd = EncryptUtils.MD5(passwd+guid);
		return passwd;
	}
	
	/**
	 * @Title: getFriendlyTime 
	* @Description: 获取友好时间
	* @param @param time
	* @param @return   
	* @return String   
	* @throws
	 */
	public static String getFriendlyTime(Date time){
		int ct = (int)((System.currentTimeMillis() - time.getTime())/1000);
		if(ct < 3600) {
			int mini = ct / 60;
			return mini<1?"刚刚":mini+"分钟前";
		}
		if(ct >= 3600 && ct < 86400)
	        return (ct / 3600)+"小时前";
	    if(ct >= 86400 && ct < 2592000){ //86400 * 30
	        int day = ct / 86400 ;          
	        return  (day>1)?day+"天前":"昨天";
	    }
	    return (new SimpleDateFormat("MM-dd")).format(time);
	}
	
    /** 
    * 利用byte数组转换InputStream------->String <功能详细描述> 
    *  
    * @param in 
    * @return 
    * @see [类、类#方法、类#成员] 
    */
	public static String inputstr2Str(InputStream in, String encode) {
		StringBuffer sb = new StringBuffer();
		byte[] b = new byte[1024];
		int len = 0;
		try {
			if (encode == null || encode.equals("")) {
				// 默认以utf-8形式
				encode = "utf-8";
			}
			while ((len = in.read(b)) != -1) {
				sb.append(new String(b, 0, len, encode));
			}
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}


	/**
	 * 判断是否全是字母
	 * @param s
	 * @return
	 */
	public static boolean isLetter(String s){
		for(int i=0;i<s.length();i++){
			char c = s.charAt(i);
			if(isLetter(c)){
				continue;
			}else{
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是否是字母
	 * @param c
	 * @return
	 */
	public static boolean isLetter(char c){
		if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
			return true;
		}
		return false;
	}

	/**
	 * 是否全是数字
	 * @param s
	 * @return
	 */
	public static boolean isNum(String s){
		for(int i=0;i<s.length();i++){
			char c = s.charAt(i);
			if(isNum(c)){
				continue;
			}else{
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是否是数字
	 * @param c
	 * @return
	 */
	public static boolean isNum(char c){
		if( c>='0' && c<='9' ){
			return true;
		}
		return false;
	}

	// 判断 正整数的格式
	public static boolean zhengshuValidate(String number) {
		Pattern pattern = Pattern.compile("^\\d+$");
		Matcher mc = pattern.matcher(number);
		return mc.matches();
	}

	/**
	 * 判断是否有中文
	 * @param str
	 * @return
	 */
	public static boolean hasChinese(String str){
		String regEx = "[\\u4e00-\\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		if(m.find()){
			System.out.println("有汉字");
			return true;
		}
		return false;
	}

	public static String removeSpechars(String s){
		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】'；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(s);
		return m.replaceAll("").trim();
	}

	/**
	 * 移除开头结尾字符
	 * @param stream
	 * @param trimstr
	 * @return
	 */
	public static String sideTrim(String stream,String trimstr){
		// null或者空字符串的时候不处理
		if (stream == null || stream.length() == 0 || trimstr == null || trimstr.length() == 0) {
			return stream;
		}

		// 结束位置
		int epos = 0;

		// 正规表达式
		String regpattern = "[" + trimstr + "]*+";
		Pattern pattern = Pattern.compile(regpattern, Pattern.CASE_INSENSITIVE);

		// 去掉结尾的指定字符
		StringBuffer buffer = new StringBuffer(stream).reverse();
		Matcher matcher = pattern.matcher(buffer);
		if (matcher.lookingAt()) {
			epos = matcher.end();
			stream = new StringBuffer(buffer.substring(epos)).reverse().toString();
		}

		// 去掉开头的指定字符
		matcher = pattern.matcher(stream);
		if (matcher.lookingAt()) {
			epos = matcher.end();
			stream = stream.substring(epos);
		}

		// 返回处理后的字符串
		return stream;
	}

	public static void teststack(){
		StackTraceElement stack[] = (new Throwable()).getStackTrace();
		for (int i = 0; i < stack.length; i++) {
			StackTraceElement ste = stack[i];
			System.out.println(ste.getClassName() + "." + ste.getMethodName() + "(...)");
			System.out.println(i+"--"+ste.getMethodName()+"--"+ste.getFileName() + "--" + ste.getLineNumber());
		}
	}

	// 将字符串转成hash值
	public static int toHash(String key) {
		int arraySize = 11113; // 数组大小一般取质数
		int hashCode = 0;
		for (int i = 0; i < key.length(); i++) { // 从字符串的左边开始计算
			int letterValue = key.charAt(i) - 96;// 将获取到的字符串转换成数字，比如a的码值是97，则97-96=1
													// 就代表a的值，同理b=2；
			hashCode = ((hashCode << 5) + letterValue) % arraySize;// 防止编码溢出，对每步结果都进行取模运算
		}
		return hashCode;
	}
	
	public static void main(String[] args) throws Exception {

		/*String s = " 　代扣代缴　\r\n ";

		String r = sideTrim(s,"　 \n\r");
		System.out.println("|"+r+"|");*/
	}

}
